package com.atsongyr.springCloud.lb;

import org.checkerframework.checker.units.qual.A;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 手写 负载均衡实现类
 * @author songyurui
 */
@Component
public class MyLB implements LoadBalancer{

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement(){
        // 当前请求集群次数
        int currentIndex;
        int nextIndex;
        do{
            currentIndex = this.atomicInteger.get();
//            2147483647 Integer最大值
            nextIndex = currentIndex >= Integer.MAX_VALUE  ? 0 : currentIndex + 1;
        }while (!this.atomicInteger.compareAndSet(currentIndex,nextIndex));
        /**
         * while 逻辑介绍
         * when currentIndex > nextIndex while return true
         * so !while = false
         * when !currentIndex <= nextIndex while return !false  = true
         * currentIndex = nextIndex and return nextIndex
         */
        // 当前大于期望值，就修改，并返回true（while取反）
        System.out.println("*********第几次访问，次数next:"+nextIndex);
        return nextIndex;
    }

    /**
     * 通过当前访问次数，除以集群个数，取余数，作为最后使用服务的index
     * @param serviceInstanceList   集群个数
     * @return ServiceInstance
     */
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstanceList) {
        int index = getAndIncrement() % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }
}
